const http = require('http');

const PORT = 3000;

function sendJSON(res, obj, status = 200) {
  const body = JSON.stringify(obj);
  res.writeHead(status, {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(body),
  });
  res.end(body);
}

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/api/hello') {
    sendJSON(res, { message: 'hello world' });
    return;
  }
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('not found');
});

server.listen(PORT, () => {
  console.log('shim-once listening on port', PORT);
  // make a single request to the server
  http.get(`http://127.0.0.1:${PORT}/api/hello`, (res) => {
    let data = '';
    res.on('data', (chunk) => { data += chunk; });
    res.on('end', () => {
      console.log('got response:', data);
      server.close(() => process.exit(0));
    });
  }).on('error', (e) => {
    console.error('request error', e.message);
    server.close(() => process.exit(1));
  });
});
